#include "DYWorkerThreadMan.h"

DYWorkerThreadMan::DYWorkerThreadMan(void)
{
	m_bWorking = FALSE;
	for(int i=0;i<MAX_WORKER_THD_COUNT;i++)
	{
		m_bThreadRun[i] = FALSE;
		m_pThrd[i]      = NULL;
		m_pEvent[i]     = NULL;
	}

	m_nWorkerCount  = MAX_WORKER_THD_COUNT;
}

DYWorkerThreadMan::~DYWorkerThreadMan(void)
{
	DYWorkerUnInit();
}

void DYWorkerThreadMan::DYWorkerUnInit()
{
	m_bWorking = FALSE;

	int i=0;

	for(i=0;i<MAX_WORKER_THD_COUNT;i++)
	{
		if( NULL != m_pThrd[i] )
		{
			if( 0 != pthread_join(m_tThrd[i],NULL) )
			{
			}
			m_pThrd[i] = NULL;
		}
	}

	m_nWorkerCount = 0;

}

int DYWorkerThreadMan::DYWorkerInit( int nCount )
{
	DYWorkerUnInit();

	do
	{	
		m_bWorking     = TRUE;

		if( nCount < 0 || nCount > MAX_WORKER_THD_COUNT )
		{
			m_nWorkerCount = 2;
		}
		else
		{
			m_nWorkerCount = nCount;
		}


		int i=0;
		for(i=0;i<m_nWorkerCount;i++)
		{
			m_arInfo[i].pThis   = this;
			m_arInfo[i].nThread = i;

			m_bThreadRun[i] = TRUE;
			if( pthread_create( &(m_tThrd[i]), NULL, _DDWorkThreadThd, &(m_arInfo[i])) != 0 )
			{
				m_bThreadRun[i] = FALSE;
				break;
			}
			m_pThrd[i] = (pthread_t*)&(m_tThrd[i]);
		}

		//MySafeCloseHandle(m_hPrepareEvent);

		return TRUE;

	}while(FALSE);

	DYWorkerUnInit();

	return FALSE;
}

VOID* DYWorkerThreadMan::_DDWorkThreadThd(VOID* lParam)
{
	stThreadInfo *pInfo = (stThreadInfo*)lParam;

	DYWorkerThreadMan *pThis   = pInfo->pThis;
	int                nThread = pInfo->nThread;

	if( NULL == pThis ||
		nThread >= MAX_WORKER_THD_COUNT )
	{
		return 0;
	}

	DWORD nRet = 0;

	while( pThis->m_bThreadRun[nThread] )
	{
		try
		{
			//�߳�����
			nRet = pThis->DDListenWorkerDispatch(pThis->m_szMsgBuffer[nThread]);
		}
		catch (...)
		{
		}
	}
	
	pThis->m_bThreadRun[nThread] = FALSE;

	return pThis;
}


int  DYWorkerThreadMan::CheckWorkerThreadState()
{
// 	int i=0;
// 	for(i=0;i<m_nWorkerCount;i++)
// 	{
// 		if( FALSE == m_bThreadRun[i] && m_bWorking )
// 		{
//             ReCreateThread(i);
// 		}
// 	}

	return 0;
}


int DYWorkerThreadMan::ReCreateThread(int nThread)
{
	

	return 0;
}
